package com.jic.veteran.portal.service.impl;

import static java.lang.String.format;

import com.jic.veteran.common.service.RedisService;
import com.jic.veteran.portal.domain.CaptchaDto;
import com.jic.veteran.portal.service.CaptchaService;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * CaptchaServiceImpl.
 *
 * @author 李世伟
 * @date 2021/6/21 17:00
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {

  private static final char[] codeChar = "0123456789".toCharArray();

  private static final String CAPTCHA_KEY_FORMAT = "veteran:captcha:%s";

  @Value("${captcha.code-length:4}")
  private Integer codeLength;

  @Value("${captcha.max-validity-seconds:300}")
  private Integer maxValiditySeconds;

  @Autowired
  private RedisService redisService;

  @Override
  public CaptchaDto genCaptcha(String id) {
    String captcha = "";
    Random random = new Random();
    for (int i = 0; i < codeLength; i++) {
      int index = random.nextInt(codeChar.length);
      captcha += codeChar[index];
    }
    CaptchaDto captchaDto = new CaptchaDto();
    captchaDto.setId(id);
    captchaDto.setCaptcha(captcha);
    redisService.set(format(CAPTCHA_KEY_FORMAT, id), captcha, maxValiditySeconds);
    return captchaDto;
  }

  @Override
  public boolean verifyCaptcha(CaptchaDto dto) {
    if (dto == null) {
      return false;
    }
    String key = format(CAPTCHA_KEY_FORMAT, dto.getId());
    Object value = redisService.get(key);
    if (value == null) {
      return false;
    }
    boolean success = String.valueOf(value)
                            .equalsIgnoreCase(dto.getCaptcha());
    if (success) {
      redisService.del(key);
    }
    return success;
  }
}
